package com.test.course2;

import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

public class CounterServletContextListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        // 在 Web 应用启动时读取计数器的初始值
        int initialCount = readInitialCount();
        Counter counter = new Counter(initialCount);
        ServletContext servletContext = sce.getServletContext();
        servletContext.setAttribute("counter", counter);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

        Counter counter = (Counter) sce.getServletContext().getAttribute("counter");
        saveCount(counter.getCount());
    }

    private int readInitialCount() {
        int initialCount = 0;
        try {
            // 读取 count.properties 文件中的计数器初始值
            InputStream inputStream = getClass().getResourceAsStream("/config.properties");
            Properties properties = new Properties();
            properties.load(inputStream);
            initialCount = Integer.parseInt(properties.getProperty("count"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return initialCount;
    }

    private void saveCount(int count) {
        try {
            // 保存计数器的值到 count.properties 文件
            OutputStream outputStream = new FileOutputStream(getClass().getResource("/config.properties").getFile());
            Properties properties = new Properties();
            properties.setProperty("count", String.valueOf(count));
            properties.store(outputStream, null);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
